package com.scalar.chiptrack.operations.tapereel.actioncommands;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.release.ContactPerson;
import com.scalar.chiptrack.operations.release.ReleaseHelper;
import com.scalar.chiptrack.operations.release.dao.RelaseDAO;
import com.scalar.chiptrack.operations.release.forms.ReleaseInfoSetupForm;
import com.scalar.chiptrack.operations.tapereel.TapeReelRequest;
import com.scalar.chiptrack.operations.tapereel.TapeReelRequestLot;
import com.scalar.chiptrack.operations.tapereel.dao.TapeReelRequestDAO;
import com.scalar.chiptrack.operations.tapereel.forms.TapeReelRequestForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: Apr 16, 2007
 * Time: 6:25:14 PM
 */
public class TapeReelRequestCancelCommand extends ActionCommand
{

    private static final String ACTION_NAME = "/tapeReelRequest.do";

    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws ScalarException
    {
        String isCancelled                          = request.getParameter( "isCancelled" );

        TapeReelRequestForm tapeReelRequestForm     = ( TapeReelRequestForm ) form;
        TapeReelRequest tapeReelRequest             = tapeReelRequestForm.getTapeReelRequest();
        ActionForward actionForward                 = mapping.findForward( "view" );
        HttpSession mSession                        = request.getSession();
        User user                                   = ( User ) mSession.getAttribute ( SessionKeys.USER_KEY );
        HashMap<String,String> errors                              = new HashMap<String,String>();
        HashMap<String,String> info                                = new HashMap<String,String>();
        int tapeReelRequestId                       = -1;
        
        DBTransaction dbTransaction                 = null;
        boolean success                             = false;

        request.setAttribute( INFO_MESSAGES, info );
        request.setAttribute( ERROR_MESSAGES, errors );

        if ( user == null )
        {
            mSession.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME );
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.TAPE_REEL_REQUEST , User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }
        try
        {
            if( "true".equalsIgnoreCase( isCancelled ) )
            {
                actionForward = mapping.findForward( "search" );
                try
                {
                    ArrayList lotList = tapeReelRequest.getLotList();
                    TapeReelRequestLot tapeReelRequestLot = null;
                    if( lotList != null && lotList.isEmpty() == false )
                    {
                        for( int i = 0; i < lotList.size(); i++ )
                        {
                            tapeReelRequestLot = ( TapeReelRequestLot ) lotList.get( i );
                            if( tapeReelRequestLot.isChecked() )
                            {
                                tapeReelRequestLot.setCancelled( true );
                            }
                        }
                    }

                    dbTransaction = DBTransaction.getInstance();
                    dbTransaction.begin();

                    //TapeReelRequestDAO.cancelTapeReeelRequest( null, tapeReelRequest );

                    TapeReelRequestDAO.saveTapeReelRequestLotDetails( dbTransaction, tapeReelRequest );
                    TapeReelRequestDAO.updateTapeReelRequestStatus( dbTransaction, tapeReelRequest );


                    success = true;
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                    throw new ScalarException( "Could not Cancel the Tape & Reel Request to database." );
                }
                finally
                {
                    if( dbTransaction != null ){
                        if( success == true ){
                            try{
                                dbTransaction.commit();
                                info.put ( "Tape & Reel Request has been Cancelled", null );
                            }catch( Exception e ){
                                e.printStackTrace();
                                errors.put ( "Error while committing the database ", null );
                            }
                        }
                        else
                        {
                            try{
                                dbTransaction.rollback();
                                errors.put ( "Tape & Reel Request Cancellation aborted", null );
                            }catch( Exception e ){
                                e.printStackTrace();
                                errors.put ( "Error occurred while rolling back", null );
                            }
                        }
                    }
                }

                tapeReelRequestForm.setTapeReelRequest( new TapeReelRequest() );

                request.setAttribute( "partNumbersList", TapeReelRequestDAO.loadTapeAndReelFgProducts() );
                request.setAttribute( "vendorsList", TapeReelRequestDAO.getTrLocations() );
                request.setAttribute( "statusList", TapeReelRequest.getStatusList() );
                tapeReelRequestForm.getTapeReelRequest().setReqStatus("Issued_Pulled");
                info.put( "Tape & Reel Request has been Cancelled", null );    
            }
            else
            {
                try
                {
                    tapeReelRequestId = Integer.parseInt( request.getParameter( "trReqId" ) );
                }
                catch ( NumberFormatException nfe )
                {
                    tapeReelRequestId = -1;
                }

                tapeReelRequest.setTrRequestid( tapeReelRequestId );
                tapeReelRequest = TapeReelRequestDAO.loadTapeReelRerquestDetails( null, tapeReelRequest );
                tapeReelRequest.setLotList( TapeReelRequestDAO.getFGLotDetails( tapeReelRequest ) );
                tapeReelRequest.setReqStatus( TapeReelRequest.STAUS_CANCELLED );

                tapeReelRequest.setPinCount( TapeReelRequestDAO.getProcessParameter( tapeReelRequest.getTrProcessStepId(), "PIN" ));
                tapeReelRequest.setPackageType( TapeReelRequestDAO.getProcessParameter( tapeReelRequest.getTrProcessStepId(), "PACKAGE ID" ));
                //tapeReelRequest.setVendorContactPersonsList(TapeReelRequestDAO.loadTapeReelAlertMails(null, tapeReelRequest));

                ReleaseInfoSetupForm releaseInfoSetupForm = null;
                releaseInfoSetupForm = new ReleaseInfoSetupForm();
                releaseInfoSetupForm.setVendorId(tapeReelRequest.getVendorId());
                releaseInfoSetupForm.setCategory("PROD");
                RelaseDAO.loadReleaseInfoSetup("Class Store", releaseInfoSetupForm);

                ArrayList<ContactPerson> vendorContactPersonsList = RelaseDAO.loadVendorContactPersonsList(null, releaseInfoSetupForm.getReleaseInfoSetupId());
                tapeReelRequest.setTrRequestAlerts(ReleaseHelper.getContactPersonsAsString("email", vendorContactPersonsList));
                ArrayList<ContactPerson> contactPersonsList = RelaseDAO.loadContactPersonsList(releaseInfoSetupForm.getReleaseInfoSetupId());
                tapeReelRequest.setInternalContactPersonEmail(ReleaseHelper.getContactPersonsAsString("email", contactPersonsList));
                tapeReelRequest.setVendorContactPersonsList(vendorContactPersonsList);
                tapeReelRequest.setContactPersonsList(contactPersonsList);
                tapeReelRequestForm.setTapeReelRequest(tapeReelRequest);

                request.setAttribute( "isCancel", "true" );
            }
      }
      catch ( Exception e)
      {
            errors.put( "Could not save the Tape & Reel Request", null );
            request.setAttribute( "partNumbersList",  TapeReelRequestDAO.loadTapeAndReelFgProducts() );
            request.setAttribute( "vendorsList", TapeReelRequestDAO.getTrLocations() );
            request.setAttribute( "statusList", TapeReelRequest.getStatusList() );
            tapeReelRequestForm.getTapeReelRequest().setReqStatus("Issued_Pulled");
            actionForward = mapping.findForward( "search" );
      }

      return actionForward;
    }
}
